﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Primitives;
using OpenIddict.Abstractions;
using System.Security.Claims;

namespace Net8.Identity.Server.Services
{
    /// <summary>
    /// 公用服务类/变量
    /// </summary>
    public class AuthorizationService
    {
        // 解析 OAuth 请求参数 (Form or Query)
        public IDictionary<string, StringValues> ParseOAuthParameters(HttpContext httpContext, List<string> excluding = null)
        {
            excluding ??= new List<string>();
            var parameters = new Dictionary<string, StringValues>();

            if (httpContext.Request.HasFormContentType)
            {
                parameters = httpContext.Request.Form
                    .Where(pair => !excluding.Contains(pair.Key))
                    .ToDictionary(pair => pair.Key, pair => pair.Value);
            }
            else
            {
                parameters = httpContext.Request.Query
                    .Where(pair => !excluding.Contains(pair.Key))
                    .ToDictionary(pair => pair.Key, pair => pair.Value);
            }
            return parameters;
        }

        /// <summary>
        /// 构建重定向地址
        /// </summary>
        /// <param name="request"></param>
        /// <param name="oAuthParameters"></param>
        /// <returns></returns>
        public string BuildRedirectUrl(HttpRequest request, IDictionary<string, StringValues> oAuthParameters)
        {
            var queryString = QueryString.Create(oAuthParameters);

            // Combine PathBase, Path, and the new QueryString
            var url = request.PathBase + request.Path + queryString;
            return url;
        }

        /// <summary>
        /// 验证授权状态
        /// </summary>
        /// <param name="authenticateResult"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public bool IsAuthenticated(AuthenticateResult authenticateResult, OpenIddictRequest request)
        {
            //拒绝授权
            if (!authenticateResult.Succeeded)
            {
                return false;
            }
            //过期
            if (request.MaxAge.HasValue && authenticateResult.Properties != null)
            {
                var maxAgeSeconds = TimeSpan.FromSeconds(request.MaxAge.Value);

                var expired = !authenticateResult.Properties.IssuedUtc.HasValue ||
                              DateTimeOffset.UtcNow - authenticateResult.Properties.IssuedUtc > maxAgeSeconds;
                if (expired)
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// 设置令牌归属
        /// </summary>
        /// <param name="identity"></param>
        /// <param name="claim"></param>
        /// <returns></returns>
        public static List<string> GetDestinations(ClaimsIdentity identity, Claim claim)
        {
            var destinations = new List<string>();

            if (claim.Type is OpenIddictConstants.Claims.Name or OpenIddictConstants.Claims.Email)
            {
                destinations.Add(OpenIddictConstants.Destinations.AccessToken);

                if (identity.HasScope(OpenIddictConstants.Scopes.OpenId))
                {
                    destinations.Add(OpenIddictConstants.Destinations.IdentityToken);
                }
            }
            return destinations;
        }
    }
}
